<template>
  <div class="package-config-page">
    <!-- 页面头部 -->
    <el-card class="page-header">
      <div class="header-content">
        <h2>包裹配置</h2>
        <div class="header-actions">
          <AppButton variant="delete" :disabled="selectedConfigs.length === 0" @click="batchDelete">批量删除</AppButton>
          <AppButton variant="add" @click="handleAddConfig">添加配置</AppButton>
        </div>
      </div>
    </el-card>

    <!-- 搜索过滤区域 -->
    <el-card class="filter-section">
      <el-form :model="searchParams.param" label-width="100px" class="search-form">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="包裹类型">
              <el-input 
                v-model="searchParams.param.packageType" 
                placeholder="请输入包裹类型"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="重量范围">
              <el-input 
                v-model="searchParams.param.weightRange" 
                placeholder="请输入重量范围"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="收费标准">
              <el-input 
                v-model="searchParams.param.feeStandards" 
                placeholder="请输入收费标准"
                clearable
                type="number"
                step="0.01"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="searchParams.param.isDel" placeholder="请选择状态" clearable>
                <el-option label="全部状态" value="" />
                <el-option label="正常" value="0" />
                <el-option label="已删除" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item>
              <AppButton variant="search" @click="handleSearch">搜索</AppButton>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 包裹配置表格 -->
    <el-card class="table-card">
      <el-table 
        :data="configs" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="配置ID" prop="id" width="280" show-overflow-tooltip />
        <el-table-column label="包裹类型" prop="packageType" min-width="120">
          <template #default="{ row }">
            <el-tag type="primary" size="small">{{ row.packageType || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="重量范围" prop="weightRange" min-width="150">
          <template #default="{ row }">
            <span class="weight-range">{{ row.weightRange || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收费标准" prop="feeStandards" min-width="120">
          <template #default="{ row }">
            <div class="fee-info">
              <span class="fee-amount">¥{{ row.feeStandards || '0.00' }}</span>
              <span class="fee-unit">元</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ row.createTime || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="{ row }">
            {{ row.updateTime || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editConfig(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <AppButton variant="delete" size="small" @click="handleDeleteConfig(row)">删除</AppButton>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalConfigs"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 包裹配置新增/编辑对话框 -->
    <PackageConfigDialog 
      v-model="showConfigDialog"
      :is-edit="isEditMode"
      :config-data="currentConfig"
      @success="handleConfigSuccess"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getPackageConfigList, deletePackageConfig, batchDeletePackageConfigs } from '@/api/express'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Edit } from '@element-plus/icons-vue'
import AppButton from '@/components/AppButton.vue'
import PackageConfigDialog from '@/components/PackageConfigDialog.vue'

const currentPage = ref(1)
const pageSize = ref(10)
const selectedConfigs = ref([])
const loading = ref(false)
const configs = ref([])
const totalConfigs = ref(0)

// 配置对话框相关状态
const showConfigDialog = ref(false)
const isEditMode = ref(false)
const currentConfig = ref({})

// 搜索参数
const searchParams = ref({
  page: 1,
  pageSize: 10,
  param: {
    id: '',
    packageType: '',
    weightRange: '',
    feeStandards: '',
    isDel: '0'
  }
})

// 获取包裹配置列表
const fetchConfigs = async () => {
  try {
    loading.value = true
    
    // 更新分页参数
    searchParams.value.page = currentPage.value
    searchParams.value.pageSize = pageSize.value
    
    const response = await getPackageConfigList(searchParams.value)
    
    // 根据后端返回的数据结构处理: { list: [...], total, page, pageSize }
    if (response) {
      configs.value = response.list || []
      totalConfigs.value = response.total || 0
      currentPage.value = response.page || currentPage.value
      pageSize.value = response.pageSize || pageSize.value
    } else {
      configs.value = []
      totalConfigs.value = 0
    }
  } catch (error) {
    console.error('获取包裹配置列表失败:', error)
    configs.value = []
    totalConfigs.value = 0
    ElMessage.error('获取包裹配置列表失败')
  } finally {
    loading.value = false
  }
}

// 计算总页数
const totalPages = computed(() => Math.ceil(totalConfigs.value / pageSize.value))

// 搜索功能
const handleSearch = () => {
  currentPage.value = 1
  fetchConfigs()
}

// 重置搜索条件
const handleReset = () => {
  searchParams.value.param = {
    id: '',
    packageType: '',
    weightRange: '',
    feeStandards: '',
    isDel: '0'
  }
  currentPage.value = 1
  fetchConfigs()
}

// 分页处理
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchConfigs()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchConfigs()
}

// 表格选择处理
const handleSelectionChange = (selection) => {
  selectedConfigs.value = selection.map(item => item.id)
}

// 添加配置
const handleAddConfig = () => {
  isEditMode.value = false
  currentConfig.value = {}
  showConfigDialog.value = true
}

// 编辑配置
const editConfig = (config) => {
  isEditMode.value = true
  currentConfig.value = { ...config }
  showConfigDialog.value = true
}

// 配置操作成功回调
const handleConfigSuccess = () => {
  fetchConfigs() // 刷新配置列表
}

// 删除配置
const handleDeleteConfig = async (config) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除包裹类型 ${config.packageType} 的配置吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await deletePackageConfig(config.id)
    ElMessage.success('删除配置成功')
    fetchConfigs() // 重新获取数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除配置失败:', error)
      ElMessage.error('删除配置失败')
    }
  }
}

// 批量删除配置
const batchDelete = async () => {
  if (selectedConfigs.value.length === 0) {
    ElMessage.warning('请选择要删除的配置')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedConfigs.value.length} 个配置吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await batchDeletePackageConfigs(selectedConfigs.value)
    ElMessage.success('批量删除配置成功')
    selectedConfigs.value = []
    fetchConfigs() // 重新获取数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除配置失败:', error)
      ElMessage.error('批量删除配置失败')
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchConfigs()
})
</script>

<style scoped>
.package-config-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.filter-section {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.weight-range {
  color: #262626;
  font-weight: 500;
}

.fee-info {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.fee-amount {
  font-weight: 600;
  color: #52c41a;
  font-size: 16px;
}

.fee-unit {
  font-size: 12px;
  color: #8c8c8c;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .package-config-page {
    padding: 10px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
}
</style>
